import { Extension } from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'
import { nanoid } from "nanoid";
import { message } from 'ant-design-vue';
export const pasteRules = (getEdit) => Extension.create({
    name: 'pasteRules',
    addProseMirrorPlugins() {
        return [
            new Plugin({
                key: new PluginKey('pasteRules'),
                props: {
                    handlePaste(view, event) {
                        // 获取剪贴板内容
                        const clipboardData = event.clipboardData || window.clipboardData;
                        let pastedText = clipboardData.getData('text/plain'); // 获取纯文本
                        const pastedHTML = clipboardData.getData('text/html'); // 获取HTML内容
                        // 示例：将粘贴的HTML转换为Tiptap的JSON格式
                        // const parser = new DOMParser();
                        // const doc = parser.parseFromString(pastedHTML, 'text/html');
                        // const tiptapJSON = editor.schema.nodes.doc.create(doc.body.childNodes);
                        const { state, dispatch } = view;
                        const { selection, tr } = state;
                        const { from, to, $from, $to } = selection;
                        const editor = getEdit();

                        // 获取当前富文本编辑器中的文字数量
                        const currentTextLen = editor.storage.characterCount.characters();
                        // 获取用户选择文本内容的字符数量
                        const selectedTextLen = editor.state.doc.textBetween(from, to)?.length || 0

                        // debugger
                        if (currentTextLen >= 500 && !selectedTextLen) {
                            message.error('文字数量超出限制, 粘贴失败')
                            return true
                        }

                        event.preventDefault();
                        const textLen = currentTextLen + pastedText.length
                        if (textLen > 500) {
                            // 即将被粘贴进入的内容字数 大于用户选择替换的内容, 提示用户
                            if (pastedText.length > selectedTextLen) {
                                message.success('文字超出数量限制, 已自动截取超出部分')
                            }
                            pastedText = pastedText.substring(0, 500 - (currentTextLen - selectedTextLen))
                        }
                        editor
                            .chain()
                            .deleteSelection()
                            .insertContentAt(from, pastedText)
                            .focus()
                            .run()
                        return true

                    },
                },
            })
        ]
    }
});
